package cn.leida.ruoyi.common.config;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author lei
 */
@Data
@Component
public class AppServerConfig {

    @Value("${server.port}")
    private int port;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    /**
     * (不以/结尾)
     * <p>
     * 本机访问地址: http://localhost:8080
     */
    public String localUrl() {
        return baseUrl(false, false);
    }

    public String localUrl(String path) {
        String baseUrl = localUrl();
        return urlPath(baseUrl, path);
    }

    private String urlPath(String baseUrl, String path) {
        String urlPath = StrUtil.trim(path);
        if (StrUtil.startWith(urlPath, "/")) {
            return baseUrl + path;
        }
        return baseUrl + "/" + path;
    }

    /**
     * (不以/结尾)
     * <p>
     * 局域网访问地址: http://192.168.1.8:8080
     */
    public String netUrl() {
        return baseUrl(false, true);
    }

    public String netUrl(String path) {
        String baseUrl = netUrl();
        return urlPath(baseUrl, path);
    }

    /**
     * 获取访问地址
     *
     * @param https 是否https (默认否)
     * @param netIp 是否局域网IP (默认否)
     * @return 获取访问地址
     */
    public String baseUrl(boolean https, boolean netIp) {
        StrBuilder sb = new StrBuilder();
        if (https) {
            sb.append("https");
        } else {
            sb.append("http");
        }
        sb.append("://");
        // 局域网ip
        if (netIp) {
            //192.168.1.8
            sb.append(NetUtil.getLocalhostStr());
        } else {
            sb.append("localhost");
        }
        if (port != 80) {
            sb.append(":").append(port);
        }
        String ctx = StrUtil.trim(contextPath);

        if (StrUtil.equals(ctx, "/")) {
            return sb.toString();
        }
        // 不为空
        if (StrUtil.isNotBlank(ctx)) {
            if (StrUtil.startWith(ctx, "/")) {
                sb.append(ctx);
            } else {
                sb.append("/").append(ctx);
            }
        }
        return sb.toString();
    }

    /**
     * 启动打印文档信息
     */
    @PostConstruct
    public void printUrl() {
        System.out.println(this.getClass().getSimpleName() + " : " + this);
        System.out.println("index: " + this.localUrl("index.html"));
        System.out.println("index: " + this.localUrl("index"));
        System.out.println("h2 db: " + this.localUrl("h2-console"));

        System.out.println("api: " + this.localUrl("doc.html"));
    }

}